package com.acxiom.bsh.service.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.acxiom.bsh.cache.TokenCache;
import com.acxiom.bsh.constants.ThreadLocalContextHolder;
import com.acxiom.bsh.logger.LoggerManager;
import com.acxiom.bsh.pojo.ApiToken;
import com.acxiom.bsh.pojo.KeyValue;
import com.acxiom.bsh.response.ApiResponse;
import com.acxiom.bsh.service.ApiService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.UserAvatarGetRequest;
import com.taobao.api.response.UserAvatarGetResponse;

@Service
public class ApiServiceImpl implements ApiService {

	// private static final Logger LOGGER =
	// LoggerFactory.getLogger(ApiServiceImpl.class);
	protected static final String REQUEST_HEADER_STRING = "application/json";

	@Autowired
	private RestTemplate restTemplate;

	@Value("${tp.api.url}")
	private String apiUrl;

	@Value("${brandAppKey}")
	private String brandAppKey;

	@Value("${brandAppSecret}")
	private String brandAppSecret;

	@Value("${topServiceUrl}")
	private String topServiceUrl;

	@Override
	public String getUserAvatarByMixNick(String mixNick) {
		String picUrl = null;
		try {
			TaobaoClient client = new DefaultTaobaoClient(topServiceUrl, brandAppKey, brandAppSecret);
			UserAvatarGetRequest req = new UserAvatarGetRequest();
			req.setNick(mixNick);
			UserAvatarGetResponse rsp;
			rsp = client.execute(req);
			picUrl = JSONObject.parseObject(JSONObject.parseObject(rsp.getBody()).getString("user_avatar_get_response")).getString("avatar");
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return picUrl;
	}

	public ApiResponse post(String path, Object body, KeyValue... uriVariables) {

		return exchange(getUrl(path, uriVariables), HttpMethod.POST, body, null);
	}

	public ApiResponse put(String path, String id, Object body, Map<String, Object> uriVariables) {

		String url = apiUrl + path + id;
		return exchange(url, HttpMethod.PUT, body, uriVariables);
	}

	public ApiResponse delete(String path, String id) {
		String url = apiUrl + path + id;
		return exchange(url, HttpMethod.DELETE, null, null);
	}

	public ApiResponse get(String path, KeyValue... uriVariables) {
		return exchange(getUrl(path, uriVariables), HttpMethod.GET, null, null);
	}

	@SuppressWarnings("unchecked")
	public ApiResponse exchange(String url, HttpMethod method, Object body, Map<String, Object> uriVariables) {
		HttpHeaders headers = new HttpHeaders();
		String requestId = UUID.randomUUID().toString();
		String source=null;
		try {
			if(ThreadLocalContextHolder.get()!=null) {
				source= ThreadLocalContextHolder.get().getValue();
			}
			headers.set("Accept", REQUEST_HEADER_STRING);
			headers.set("content-type", REQUEST_HEADER_STRING);
			headers.set("request-id", requestId);
			headers.set("source", source);
			LoggerManager.getApiLogger().info("Api request headers :{} ",JSONObject.toJSONString(headers));
			ApiToken apiToken = TokenCache.getApiToken();
			if (apiToken != null) {
				headers.set("token", apiToken.getToken());
			}
			if (uriVariables == null) {
				uriVariables = new HashMap<String, Object>();
			}

			@SuppressWarnings("rawtypes")
			HttpEntity requestEntity = new HttpEntity(body, headers);

			LoggerManager.getApiLogger().info("Api request start. request id: {}, url: {}, method: {}, body: {}", requestId, url, method, body != null ? JSON.toJSONString(body) : "null");
			ApiResponse response = restTemplate.exchange(url, method, requestEntity, ApiResponse.class, uriVariables).getBody();
			LoggerManager.getApiLogger().info("Api request response. request id: {}, url: {}, method: {}, response: {}", requestId, url, method, response != null ? JSON.toJSONString(response) : "null");
			return response;
		} catch (Exception e) {
			LoggerManager.getApiLogger().error("Api request error. request id: {}, url: {}, method: {}, error: {}", requestId, url, method, e.getMessage());
			e.printStackTrace();
			return null;
		}

	}

	private String getUrl(String path, KeyValue... uriVariables) {
		StringBuffer url = new StringBuffer(apiUrl + path);
		if (uriVariables != null && uriVariables.length > 0) {
			url.append("?");
			for (KeyValue v : uriVariables) {
				url.append(v.getKey()).append("=").append(v.getValue()).append("&");
				// try {
				// if (v.equals("taobao_user_nick")) {
				// url.append(v.getKey()).append("=").append(v.getValue()).append("&");
				// } else {
				// url.append(v.getKey()).append("=").append(URLEncoder.encode(v.getValue(), "UTF-8")).append("&");
				// }
				// } catch (UnsupportedEncodingException e) {
				// url.append(v.getKey()).append("=").append(v.getValue()).append("&");
				// }
			}
		}
		return url.toString();
	}

	@Override
	public String httpGet(String url) {
		System.out.println(exchange(url, HttpMethod.GET, null, null));
		return null;
	}

}
